import cv2
import numpy as np
if __name__ == '__main__':
    # 1. 图片输入
    image_np = cv2.imread("C:\\Users\\20436\Desktop\\ziqi.jpg")

    # 2. 灰度化
    image_np_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)

    # 3. 二值化
    _, image_np_thresh = cv2.threshold(
        image_np_gray,
        74,
        255,
        cv2.THRESH_BINARY_INV
    )
    # 4.高斯滤波
    no_noise_image = cv2.GaussianBlur(
        image_np_thresh,  # 要滤波的图像
        (3, 3),  # 核
        1  # SigmaX
    )
    # 5. 查找轮廓
    contours, hierarchy = cv2.findContours(
        no_noise_image,
        cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE
    )
    print(len(contours))

        # 计算最小外接圆
        # 返回值：圆心和半径
    (x, y), radius = cv2.minEnclosingCircle(contours[40])
        # 转整形
    x, y, radius = int(x), int(y), int(radius)

        # 画圆
    cv2.circle(
        image_np,  # 在哪里画
        (x, y),  # 圆心
        radius,  # 半径
        (255, 0, 0),  # 颜色
        2,  # 粗度
        cv2.LINE_AA  # 抗锯齿
    )
    cv2.imshow('contour_image', image_np)
    cv2.imwrite('contour_image.jpg', image_np)
    cv2.waitKey(0)